import Notify from '@vant/weapp/notify/notify';
import {handlePageChange} from '../../router/index'
const $api = require('../../request/index').API;

// pages/key_rent/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 2,
    active_step: 0,
    steps: [
      {text:'申请钥匙',},
      {text:'领取钥匙',},
      {text:'归还钥匙',},
    ],
    // 1.租借:
    // 可租借的房间 
    rooms: [
      {name:'1教'},
      {name:'2教'},
      {name:'创新机房'},
    ],
    // 租借选择的数据
    rent_room: '1教',
    rent_start: '',
    rent_end: '',
    // 选择组件是否显示
    show_room_select: false,
    show_start_select: false,
    show_end_select: false,
    // 时间选择区间
    cur_time: '08:00',
    min_hour: 8,
    max_hour: 22,

    // 2. 领取钥匙
    activeCollapses: [],    
    rent_key: '123',

    rent_id: 0,
    token: "",
    user_id: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    var token , user_id
    try {
      token = wx.getStorageSync('token')
      user_id = wx.getStorageSync('user_id')
      // token 必须存在
      if (!token) {
        Notify({ type: 'warning', message: '网络异常请刷新小程序', onClose: back2Home })
        return
      }

      // console.log("uid ",user_id, "token ", token)
    } catch (e) {
      console.log(e)
      Notify({ type: 'warning', message: '网络异常请刷新小程序', onClose: back2Home })
      return 
    }
    this.setData({token:token, user_id:user_id})
    
    // 加载房间列表
    $api.roomList({page_num:1}, token).then(res => {
      var roomList = res.lists.map((item)=> {
        return {name:item.room}
      })
      this.setData({rooms:roomList})
    }).catch(e => {
      console.log(e)
    }) 
    if (user_id) {
      // 加载用户借钥匙状态
      $api.userRent({user_id:parseInt(user_id)},token).then(res=>{
        if (res && res.id != -1) {
          console.log('get user rent', res)
          this.setData({
            active_step:1,
            rent_room :res.room,
            rent_start:this.timecov(res.start_time),
            rent_ent:this.timecov(res.end_time),
            rent_key:res.rent_key,
            rent_id:res.id,
          })
        }
      }).catch(e => {
        console.log(e)
      })
    }
  },
  resetData() {
    this.setData({
      rent_id: 0,
      rent_end: "",
      rent_key: "",
      rent_room: "1教",
      rent_start:"",
    })
  },
  // 时间戳转换成 HH:MM
  timecov(timestemp) {
    var dt = new Date(timestemp)
    return dt.getHours() + ":" + dt.getMinutes()
  },
  timestemp(time) {
    var dt = new Date()
    time = time.split(":")
    dt.setHours(time[0])
    dt.setMinutes(time[1])
    return dt.getTime()
  },
  // 选择框切换状态
  onToggleRoomSelect() {
    this.setData({show_room_select:!this.data.show_room_select})
  },
  onToggleStartSelect() {
    this.setData({show_start_select:!this.data.show_start_select})
  },
  onToggleEndSelect() {
    this.setData({show_end_select:!this.data.show_end_select})
  },
  // 填入选择数据
  onStartSelect(event) {
    this.setData({rent_start:event.detail})
  },
  onEndSelect(event) {
    this.setData({rent_end:event.detail})
  },
  onRoomSelect(event) {
    this.setData({rent_room:event.detail.name})
  },
  onCollapsesChange(event) {
    this.setData({activeCollapses:event.detail})
  },
  onPageChange(event) {
    handlePageChange(event.detail)
  },
  // 状态改变请求
  onApplyRent() {
    // send apply to server
    var {user_id, rent_room, rent_start, rent_end, token, user_id} = this.data
    if (!user_id) {
      Notify({ type: 'warning', message: '提出申请前请先登录'})
      return
    }
    
    $api.addRent({
      user_id:parseInt(user_id),
      room:rent_room, 
      start_time:this.timestemp(rent_start), 
      end_time:this.timestemp(rent_end)
    },token)
      .then(res => {
        console.log(res)
        this._nextStep()
      })
      .catch(e => {
        console.log(e)
        Notify({ type: 'error', message: '申请失败'})
        return 
      }) 
  },
  onRceiveRent() {
    this._nextStep()
  },
  onReturnRent() {
    var {token, rent_id} = this.data
    $api.deleteRent(null, token, rent_id).then(()=>{
      this.resetData()
    }).catch(err=>{
      console.log(err)
    })
    this._nextStep()
  },
  _nextStep() {
    this.setData({active_step: (this.data.active_step+1)%3})
  },

})